import { IvcsError } from '../base/error';
import Logger from '../base/logger';
const errorCode = {
    createError: 8001,
    startError: 8002,
    stopError: 8003,
    removeError: 8004,
    snapshotError: 8005,
    whiteboardIdError: 8006
};
/**
 * 白板类,pdf标注,证言抄录
 */
class IrtcWhiteBoard {
    // 构造方法
    constructor(irtcClient) {
        // super();
        this.irtc = irtcClient;
        const whiteboardaddedListener = eve => {
            let whiteboard = eve.whiteboard;
            Logger.info(`ivcs-js-sdk:new whiteboard add:${whiteboard},whiteboard Id,${whiteboard.id},at:${new Date().toISOString()}`);
            this.irtc.whiteboards = [... this.irtc.whiteboards, whiteboard];
        };
        this.irtc.irtcClient.addEventListener('whiteboardadded', whiteboardaddedListener);
    }

    /**
     * 添加白板监听事件，如移除
     * @param {IRtc.Conference.Whiteboard} whiteboard 
     */
    addEvent (whiteboard) {
        let remove = () => {
            Logger.info(`ivcs-js-sdk:whiteboard ${whiteboard.id} removed at:${new Date().toISOString()}`);
        };
        whiteboard.addEventListener('remove', remove);
    }

    /**
     * 创建白板
     * @param {string} name 白板名称
     * @param {string} path 白板的页面path 如/customer/static/whiteboard/board/index.html
     * @param {object} attribute 自定义属性
     * @returns Promise<IRtc.Conference.Whiteboard,Error>
     */
    create (name, path, attribute = {}) {
        return new Promise((resolve, reject) => {
            this.irtc.irtcClient.createWhiteboard(name, path, attribute).then((whiteboard) => {
                resolve(whiteboard);
            }).catch((error) => {
                Logger.error(`ivcs-js-sdk:createWhiteboard error,${error},with name:${name},path:${path},attribute:${JSON.stringify(attribute)},at:${new Date().toISOString()}`);
                reject(new IvcsError(errorCode.createError, error));
            })
        })
    }

    /**
     * 开启白板
     * @param {IRtc.Conference.Whiteboard} whiteboard 
     * @param {string} hostname 白板的前端部署主机地址 如：'https://www.abc.com'。
     * @returns Promise<iframe,Error>
     */
    start (whiteboard, hostname) {
        return new Promise((resolve, reject) => {
            this.irtc.irtcClient.startWhiteboard(hostname, whiteboard).then((iframe) => {
                resolve(iframe);
            }).catch((error) => {
                Logger.error(`ivcs-js-sdk:startWhiteboard error，whiteboard:${whiteboard},hostname:${hostname},at:${new Date().toISOString()}`);
                reject(new IvcsError(errorCode.startError, error));
            })
        })
    }


    /**
     * 根据白板id开启白板
     * @param {string} whiteboardId 
     * @param {string} hostname 白板的前端部署主机地址 如：'https://www.abc.com'。
     * @param {function} onSuccess 
     * @param {function} onFailure 
     */
    startWithId (whiteboardId, hostname, onSuccess, onFailure) {
        function getWhiteboard (item) {
            return item.id === whiteboardId;
        }
        let whiteboard = this.irtc.whiteboards.find(getWhiteboard);
        if (!whiteboard) {
            onFailure(new IvcsError(errorCode.whiteboardIdError, `whiteboardId ,${whiteboardId} is invalid`));
        } else {
            this.start(whiteboard, hostname).then((iframe) => {
                // let host = window.location.host;
                // let iframeUrl = iframe.src;
                // console.log('iframeUrl origin url', iframeUrl);
                // if (new URL(iframeUrl)) {
                //     let url = new URL(iframeUrl);
                //     let replaceUrl = iframeUrl.replace(url.host, host);
                //     iframe.src = replaceUrl;
                //     console.log('iframeUrl replace url', replaceUrl);
                // } else {
                //     Logger.error(`iframe url is invalid,at:${new Date().toISOString()}`);
                // }
                onSuccess(iframe);
            }).catch((error) => {
                onFailure(error);
            });
        }
    }

    /**
     * 关闭白板
     * @param {IRtc.Conference.Whiteboard} whiteboard 
     * @returns Promise<Void,Error>
     */
    stop (whiteboard) {
        if(!this.irtc || !this.irtc.irtcClient){
            Logger.info(`ivcs-js-sdk:stopWhiteboard whiteboard:${whiteboard} whiteboardId:${whiteboard.id}, canceled, reason: no irtcClient`);
            return Promise.resolve('canceled');
        }
        return new Promise((resolve, reject) => {
            this.irtc.irtcClient.stopWhiteboard(whiteboard).then(() => {
                resolve('ok');
            }).catch((error) => {
                Logger.error(`ivcs-js-sdk:stopWhiteboard error，whiteboard:${whiteboard},at:${new Date().toISOString()}`);
                reject(new IvcsError(errorCode.stopError, error));
            })
        })
    }

    /**
     * 根据白板id关闭白板
     * @param {string} whiteboardId 
     * @param {function} onSuccess 
     * @param {function} onFailure 
     */
    stopWithId (whiteboardId, onSuccess, onFailure) {
        function getWhiteboard (item) {
            return item.id === whiteboardId;
        }
        let whiteboard = this.irtc.whiteboards.find(getWhiteboard);
        if (!whiteboard) {
            onFailure(new IvcsError(errorCode.whiteboardIdError, `whiteboardId ,${whiteboardId} is invalid`));
        } else {
            this.stop(whiteboard).then(() => {
                onSuccess('ok');
            }).catch((error) => {
                onFailure(error);
            });
        }
    }

    /**
     * 移除白板
     * @param {IRtc.Conference.Whiteboard} whiteboard 
     * @returns Promise<Void,Error>
     */
    remove (whiteboard) {
        return new Promise((resolve, reject) => {
            this.irtc.irtcClient.removeWhiteboard(whiteboard).then(() => {
                resolve('ok');
            }).catch((error) => {
                Logger.error(`ivcs-js-sdk:removeWhiteboard error，whiteboard:${whiteboard},at:${new Date().toISOString()}`);
                reject(new IvcsError(errorCode.removeError, error));
            })
        })
    }

    /**
     * 根据白板id删除白板
     * @param {string} whiteboardId 
     * @param {function} onSuccess 
     * @param {function} onFailure 
     */
    removeWithId (whiteboardId, onSuccess, onFailure) {
        function getWhiteboard (item) {
            return item.id === whiteboardId;
        }
        let whiteboard = this.irtc.whiteboards.find(getWhiteboard);
        if (!whiteboard) {
            onFailure(new IvcsError(errorCode.whiteboardIdError, `whiteboardId ,${whiteboardId} is invalid`));
        } else {
            this.remove(whiteboard).then(() => {
                onSuccess('ok');
            }).catch((error) => {
                onFailure(error);
            });
        }
    }

    /**
     * 截图白板
     * @param {IRtc.Conference.Whiteboard} whiteboard 
     * @returns Promise<Object,Error>
     */
    snapshot (whiteboard) {
        return new Promise((resolve, reject) => {
            this.irtc.irtcClient.snapshot(whiteboard).then((data) => {
                // {front:string(base64),background,metaData}
                resolve(data);
            }).catch((error) => {
                Logger.error(`ivcs-js-sdk:snapshot error，whiteboard:${whiteboard},at:${new Date().toISOString()}`);
                reject(new IvcsError(errorCode.snapshotError, error));
            })
        })
    }


    /**
     * 根据白板id截图
     * @param {string} whiteboardId 
     * @param {function} onSuccess {front:string(base64),background,metaData}
     * @param {function} onFailure 
     */
    snapshotWithId (whiteboardId, onSuccess, onFailure) {
        function getWhiteboard (item) {
            return item.id === whiteboardId;
        }
        let whiteboard = this.irtc.whiteboards.find(getWhiteboard);
        if (!whiteboard) {
            onFailure(new IvcsError(errorCode.whiteboardIdError, `whiteboardId ,${whiteboardId} is invalid`));
        } else {
            this.snapshot(whiteboard).then((resp) => {
                onSuccess(resp);
            }).catch((error) => {
                onFailure(error);
            });
        }
    }

}

export { IrtcWhiteBoard };